package smartcrud.spring.models.cms;

import java.io.File;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import smartcrud.common.orm.Page;
import smartcrud.common.orm.PropertyFilter;

@Service
public class PostServiceJdbcImpl implements PostService {
	private static final Log logger = LogFactory
			.getLog(PostServiceJdbcImpl.class);
	
	@Autowired
	private PostDao postDao;

	@Autowired
	private AttachmentDao attachmentDao;

	@Override
	public Post createPost(Post o) {
		Post post = postDao.createPost(o);
		attachmentDao.updateAttachmentsWithPostId(post.getAttachments(),
				post.getId());
		return post;
	}

	@Override
	public void deletePost(Long id) {

		// delete post
		postDao.deletePost(id);

		// delete related attachments
		List<Attachment> attachments = attachmentDao.findAttachmentsByPostId(id);

		ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest req = sra.getRequest();
		ServletContext ctx = req.getSession().getServletContext();
		for (Attachment attachment : attachments) {
			// delete from disk
			String url = attachment.getUrl();
			String realpath = ctx.getRealPath(url);
			logger.info("realpath="+ realpath);
			
			File attachmentFile = new File(realpath);
			
			if (attachmentFile.exists()) {
				logger.info("deleting " + attachmentFile.getAbsolutePath());
				attachmentFile.delete();
			}
			
		}

		// delete from table.
		attachmentDao.deleteAttachmentsByPostId(id);

	}

	@Override
	public void updatePost(Post o) {
		postDao.updatePost(o);
	}

	@Override
	public Post findPostById(Long id) {
		Post post = postDao.findPostById(id);
		List<Attachment> attachments = attachmentDao
				.findAttachmentsByPostId(id);
		post.setAttachments(attachments);

		return post;
	}

	@Override
	public Post findPostAndAttachments(Long id) {
		Post post = postDao.findPostById(id);
		List<Attachment> attachments = attachmentDao
				.findAttachmentsByPostId(id);
		post.setAttachments(attachments);

		return post;
	}

	@Override
	public List<Post> findAllPosts() {
		return postDao.findAllPosts();
	}

	@Override
	public int count() {
		return postDao.count();
	}

	@Override
	public Page<Post> findByPage(Page<Post> page,
			final List<PropertyFilter> filters) {
		return postDao.findByPage(page, filters);
	}
}
